package com.sxz.sbs.module.client.qr;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.design.widget.BottomSheetDialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nanchen.compresshelper.CompressHelper;
import com.sxz.sbs.R;
import com.sxz.sbs.applibrary.StatusBarUtil;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.base.BasePresenter;
import com.sxz.sbs.module.client.qr.camera.CameraManager;
import com.sxz.sbs.module.client.qr.decode.DecodeThread;
import com.sxz.sbs.module.client.qr.decode.DecodeUtils;
import com.sxz.sbs.module.client.qr.utils.InactivityTimer;
import com.tian.photopicker.PhotoPicker;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;

/**
 * 扫描合同
 */
public class CaptureActivity extends BaseActivity implements SurfaceHolder.Callback{
    public static final int IMAGE_PICKER_REQUEST_CODE = 100;
    @BindView(R.id.capture_preview)
    SurfaceView capturePreview;
    @BindView(R.id.iv_title_back)
    ImageView ivBack;
    @BindView(R.id.capture_scan_line)
    ImageView captureScanLine;
    @BindView(R.id.tv_scan_pic)
    TextView capturePictureBtn;
    @BindView(R.id.capture_crop_view)
    RelativeLayout captureCropView;
    @BindView(R.id.capture_container)
    RelativeLayout captureContainer;
    @BindView(R.id.cb_lamp_light)
    CheckBox checkBox;
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private boolean hasSurface;
    private InactivityTimer mInactivityTimer;
    private int mQrcodeCropWidth = 0;
    private int mQrcodeCropHeight = 0;
    private int mBarcodeCropWidth = 0;
    private int mBarcodeCropHeight = 0;
    private Rect cropRect;
    private int dataMode = DecodeUtils.DECODE_DATA_MODE_ALL;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scan_contract;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void init() {
        StatusBarUtil.enableTranslucentStatusbar(this);
        hasSurface = false;
        mInactivityTimer = new InactivityTimer(this);
        initCropViewAnimator();
        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
                0.9f);
        animation.setDuration(3000);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.REVERSE);
        captureScanLine.startAnimation(animation);
        capturePictureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoPicker.builder().setSelectPhotoCount(1).
                        start(CaptureActivity.this,IMAGE_PICKER_REQUEST_CODE);
            }
        });
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cameraManager.setTorch(true);
                    checkBox.setText("关闭手电筒");
                } else {
                    cameraManager.setTorch(false);
                    checkBox.setText("打开手电筒");
                }
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
    private void initCropViewAnimator() {
        mQrcodeCropWidth = getResources().getDimensionPixelSize(R.dimen.qrcode_crop_width);
        mQrcodeCropHeight = getResources().getDimensionPixelSize(R.dimen.qrcode_crop_height);
        mBarcodeCropWidth = getResources().getDimensionPixelSize(R.dimen.barcode_crop_width);
        mBarcodeCropHeight = getResources().getDimensionPixelSize(R.dimen.barcode_crop_height);
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;

        int[] location = new int[2];
        captureCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1];

        int cropWidth = captureCropView.getWidth();
        int cropHeight = captureCropView.getHeight();

        int containerWidth = captureContainer.getWidth();
        int containerHeight = captureContainer.getHeight();

        int x = cropLeft * cameraWidth / containerWidth;
        int y = cropTop * cameraHeight / containerHeight;

        int width = cropWidth * cameraWidth / containerWidth;
        int height = cropHeight * cameraHeight / containerHeight;

        setCropRect(new Rect(x, y, width + x, height + y));
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getApplication());
        handler = null;
        if (hasSurface) {
            initCamera(capturePreview.getHolder());
        } else {
            capturePreview.getHolder().addCallback(this);
        }

        mInactivityTimer.onResume();
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }

        mInactivityTimer.onPause();
        cameraManager.closeDriver();
        if (!hasSurface) {
            capturePreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mInactivityTimer.shutdown();
        super.onDestroy();
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e("TAG", "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!hasSurface) {
            hasSurface = true;
//            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        initCamera(holder);
    }

    /**
     * A valid barcode has been found, so give an indication of success and show the results.
     */
    public void handleDecode(String result, Bundle bundle) {
        mInactivityTimer.onActivity();
        if (!TextUtils.isEmpty(result) && RegexUtils.isURL(result)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(result));
            startActivity(intent);
        } else if (TextUtils.isEmpty(result)){
           ToastUtils.showShort("未扫描到结果");
        } else {
            Intent intent = new Intent();
            intent.putExtra("result_code", result);
            setResult(1000,intent);
            finish();
        }
    }

    private void onCameraPreviewSuccess() {
        initCrop();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            //Log.w(TAG_LOG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager);
            }

            onCameraPreviewSuccess();
        } catch (IOException ioe) {

            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {

            displayFrameworkBugMessageAndExit();
        }

    }

    private void displayFrameworkBugMessageAndExit() {
        ToastUtils.showShort("出现错误，请稍后再试");
        finish();

    }

    public Rect getCropRect() {
        return cropRect;
    }

    public void setCropRect(Rect cropRect) {
        this.cropRect = cropRect;
    }

    public int getDataMode() {
        return dataMode;
    }

    public void setDataMode(int dataMode) {
        this.dataMode = dataMode;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        List<String> result = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
        if(result != null && result.size() >0) {
            if (result.get(0) != null) {
                File newFile = new CompressHelper.Builder(this)
                        .setMaxWidth(720)
                        .setMaxHeight(1080)
                        .setQuality(50)
                        .setFileName(System.currentTimeMillis()+"")
                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES).getAbsolutePath())
                        .build()
                        .compressToFile(new File(result.get(0)));
                Bitmap bitmap = BitmapFactory.decodeFile(newFile.getAbsolutePath());
                String resultZxing = new DecodeUtils(DecodeUtils.DECODE_DATA_MODE_ALL)
                        .decodeWithZxing(bitmap);
                Bundle extras = new Bundle();
                extras.putInt(DecodeThread.DECODE_MODE, DecodeUtils.DECODE_MODE_ZXING);
                handleDecode(resultZxing, extras);
            }
        }
    }
}
